package com.third.clock.ui.fragment;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.third.clock.R;
import com.third.clock.bean.ReportEntity;
import com.third.clock.common.LogUtils;
import com.third.clock.manager.WindowMessageManager;
import com.third.clock.ui.model.IMindsFragmentView;
import com.third.clock.ui.model.adapter.InBoxAdapter;
import com.third.clock.ui.model.presenter.MindsFragmentPresenter;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.List;

import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * Created by Administrator on 2018/7/23 0023.
 */

public class MindsFragment extends Fragment implements IBaseFragment,View.OnClickListener,SwipeRefreshLayout.OnRefreshListener,SwipeMenuRecyclerView.LoadMoreListener,SwipeItemClickListener,IMindsFragmentView{

    private static final String TAG="MindsFragment";

    protected Activity ctx;

    protected View layout;

    private SegmentedGroup mSegmentedGroup;

    private RadioButton mRadioButtonInbox;

    private RadioButton mRadioButtonReport;

    private View mInboxView;

    private View mReportView;

    private SwipeMenuRecyclerView mRecyclerView;

    private SwipeRefreshLayout mSwiperefreshlayout;

    private MindsFragmentPresenter mindsFragmentPresenter;

    private InBoxAdapter mInBoxAdapter;

    private Button mButtonReport;

    private EditText mEditTextTitle;

    private EditText mEditTextConent;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (layout == null) {
            ctx = this.getActivity();
            layout = ctx.getLayoutInflater().inflate(R.layout.fragment_minds, null);

        } else {
            ViewGroup parent = (ViewGroup) layout.getParent();
            if (parent != null) {
                parent.removeView(layout);
            }
        }
        return layout;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initSwipeRefreshLayout();
    }

    @Override
    public void onResume() {
        super.onResume();
        initEvent();
        LogUtils.e(TAG,"onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        WindowMessageManager.getInstance().dismiss();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initView(){

        mSegmentedGroup = (SegmentedGroup) layout.findViewById(R.id.segmentedgroup);
        mRadioButtonInbox= (RadioButton) layout.findViewById(R.id.radioButtonOne);
        mRadioButtonReport= (RadioButton) layout.findViewById(R.id.radioButtonTwo);
        mInboxView=layout.findViewById(R.id.inbox_view);
        mReportView=layout.findViewById(R.id.report_view);
        mRecyclerView= (SwipeMenuRecyclerView) layout.findViewById(R.id.recyclerview);
        mSwiperefreshlayout= (SwipeRefreshLayout) layout.findViewById(R.id.swiperefreshlayout);
        mButtonReport= (Button) layout.findViewById(R.id.button_report);
        mEditTextTitle= (EditText) layout.findViewById(R.id.edittext_title);
        mEditTextConent=(EditText) layout.findViewById(R.id.edittext_conent);

        mRadioButtonInbox.setOnClickListener(this);
        mRadioButtonReport.setOnClickListener(this);
        mButtonReport.setOnClickListener(this);

        LinearLayoutManager manager=new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setSwipeItemClickListener(this); // RecyclerView Item点击监听。
        mRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        mRecyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);
        mRecyclerView.useDefaultLoadMore(); // 使用默认的加载更多的View。
        mRecyclerView.setLoadMoreListener(this); // 加载更多的监听。

        mindsFragmentPresenter=new MindsFragmentPresenter(getActivity());
        mindsFragmentPresenter.setIMindsFragmentView(this);

        mInBoxAdapter=new InBoxAdapter(getActivity());
        mRecyclerView.setAdapter(mInBoxAdapter);
    }

    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.radioButtonOne:
               switchTab(R.id.radioButtonOne);
               initEvent();
               break;
           case R.id.radioButtonTwo:
               switchTab(R.id.radioButtonTwo);
               break;
           case R.id.button_report:
               mindsFragmentPresenter.postReport(mEditTextTitle.getText().toString().toString(),mEditTextConent.getText().toString().trim());
               break;
       }
    }

    private void switchTab(int id){
        if(id==R.id.radioButtonOne){
            mInboxView.setVisibility(View.VISIBLE);
            mReportView.setVisibility(View.GONE);
        }else if(id==R.id.radioButtonTwo){
            mInboxView.setVisibility(View.GONE);
            mReportView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化下拉刷新控件，SwipeRefreshLayout
     */
    private void initSwipeRefreshLayout() {
        //设置刷新进度条的颜色变化，最多可以设置 4 种，加载的颜色是循环播放的。
        mSwiperefreshlayout.setColorSchemeResources(R.color.colorAccent);
        //设置手指在屏幕上下拉多少会触发下拉刷新
        mSwiperefreshlayout.setDistanceToTriggerSync(300);
        //设置下拉刷新的圆圈背景颜色
        mSwiperefreshlayout.setProgressBackgroundColorSchemeColor(Color.WHITE);
        //设置下拉刷新的圆圈大小
        mSwiperefreshlayout.setSize(SwipeRefreshLayout.DEFAULT);
        mSwiperefreshlayout.setOnRefreshListener(this);

    }

    @Override
    public void startRefreshing() {
        mSwiperefreshlayout.setRefreshing(true);
    }

    @Override
    public void stopRefreshing() {
        mSwiperefreshlayout.setRefreshing(false);
    }

    @Override
    public void onLoadmorestop() {
        // 数据完更多数据，一定要掉用这个方法。
        // 第一个参数：表示此次数据是否为空。
        // 第二个参数：表示是否还有更多数据。
        mRecyclerView.loadMoreFinish(false, true);
    }

    @Override
    public void onRefreshData(MindsFragmentPresenter.LoadType type,List<ReportEntity> list) {
        if(mInBoxAdapter!=null) {
            if(type== MindsFragmentPresenter.LoadType.REFRESH) {
                mInBoxAdapter.setList(list);
                // 第一次加载数据：一定要调用这个方法，否则不会触发加载更多。
                // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
                // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
                if(list==null||list.size()==0) {
                    mRecyclerView.loadMoreFinish(false, false);
                }else{
                    mRecyclerView.loadMoreFinish(false, true);
                }
            }else{
                mInBoxAdapter.addList(list);
            }
        }
    }

    @Override
    public void onRefresh() {
        //开始执行刷新
        if(mindsFragmentPresenter!=null) mindsFragmentPresenter.onRefresh(MindsFragmentPresenter.LoadType.REFRESH);
    }

    @Override
    public void onLoadMore() {
        if(mindsFragmentPresenter!=null) mindsFragmentPresenter.onRefresh(MindsFragmentPresenter.LoadType.LOADMORE);
    }

    @Override
    public void onItemClick(View itemView, int position) {
        //Toast.makeText(getActivity(), "第" + position + "个", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void initEvent() {
         //开始执行刷新
        if(mindsFragmentPresenter!=null)mindsFragmentPresenter.onRefresh(MindsFragmentPresenter.LoadType.REFRESH);
    }

    @Override
    public void onReportFail(String message) {
        if(!TextUtils.isEmpty(message)&&getActivity()!=null&&!getActivity().isFinishing()){
            WindowMessageManager.getInstance().showSuccessWithStatus(getActivity(),"打卡成功");
        }
    }

    @Override
    public void onReportSuccess() {
        if(getActivity()!=null&&!getActivity().isFinishing()) {
            new SVProgressHUD(getActivity()).showSuccessWithStatus("提交成功");
        }
    }

    @Override
    public void onRemoveSuccess(int position) {
        if(mInBoxAdapter!=null){
            mInBoxAdapter.remove(position);
        }
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = 200;

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity())
                        .setBackground(R.drawable.selector_red)
                        .setImage(R.mipmap.ic_action_delete)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。

                SwipeMenuItem addItem = new SwipeMenuItem(getActivity())
                        .setBackground(R.drawable.selector_green)
                        .setText("取消")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。
            }
        }
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                //Toast.makeText(getActivity(), "list第" + adapterPosition + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
                if(menuPosition==0){
                    //开始执行删除
                    mindsFragmentPresenter.removeReport(adapterPosition,mInBoxAdapter.getEntity(adapterPosition));
                }
            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {

            }
        }
    };

}
